﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class XIncubator : MonoBehaviour
{
    private Dictionary<string, Queue<GameObject>> _key2Objs = new Dictionary<string, Queue<GameObject>>();
    public async void DequeueAsync(string key, Action<GameObject> callBack)
    {
        Queue<GameObject> objs;
        if(!_key2Objs.TryGetValue(key, out objs))
        {
            objs = new Queue<GameObject>();
            _key2Objs[key] = objs;
        }

        GameObject obj;
        if(objs.Count > 0)
        {
            obj = objs.Dequeue();
            obj.SetActive(true);
            obj.transform.SetParent(null, false);
            callBack(obj);
            return;
        }

        var op = XInstanceMgr.InstantiateAsync(key);
        obj = await op.Task;
        obj.name = obj.name +"唯一id:"+ obj.GetInstanceID();
        callBack(obj);
    }

    public void Enqueue(string key, UnityEngine.GameObject obj)
    {
        Queue<GameObject> objs;
        if (!_key2Objs.TryGetValue(key, out objs))
        {
            Debug.LogError("Enqueue -> Can not find key:" + key);
            return;
        }
        objs.Enqueue(obj);
        obj.SetActive(false);
        obj.transform.SetParent(this.transform, false);
    }

    protected virtual void OnDestroy()
    {
        foreach (var objs in _key2Objs.Values)
        {
            while (objs.Count > 0)
            {
                XInstanceMgr.ReleaseInstance(objs.Dequeue());
            }
        }
    }
}
